package com.example.web.gateway.filter;

import com.example.entity.ResMsgBody;
import com.example.entity.ReturnCode;
import com.example.utils.TypicalRepException;
import com.example.web.gateway.service.AuthService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Component
@Order(-2)
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private AuthService authService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        try {
            ServerHttpRequest request = exchange.getRequest();
            ServerHttpResponse response = exchange.getResponse();

            //1.判断当前请求路径是否为登录请求,如果是,则直接放行
            String path = request.getURI().getPath();
            if ("/api/oauth/login".equals(path)){
                //直接放行
                return chain.filter(exchange);
            }

            //2.从cookie中获取jti的值,如果该值不存在,拒绝本次访问
            String jti = authService.getJtiFromCookie(request);
            if (StringUtils.isEmpty(jti) /*|| UrlFilter.hasAuthorize(path)*/){

                //cookie不存在认证信息  拒绝访问
                byte[] bytes = ResMsgBody.ERROR_LOST_AUHT.getBytes(StandardCharsets.UTF_8);
                DataBuffer buffer = response.bufferFactory().wrap(bytes);
                return response.writeWith(Mono.just(buffer));

                //response.setStatusCode(HttpStatus.UNAUTHORIZED);
                //return response.setComplete();
            }

            //3.从redis中获取jwt的值,如果该值不存在,拒绝本次访问
            String jwt = authService.getJwtFromRedis(jti);
            if (StringUtils.isEmpty(jwt)){

                //令牌失效  拒绝访问
                byte[] bytes = ResMsgBody.ERROR_AUHT_EXPIRED.getBytes(StandardCharsets.UTF_8);
                DataBuffer buffer = response.bufferFactory().wrap(bytes);
                return response.writeWith(Mono.just(buffer));
                //response.setStatusCode(HttpStatus.UNAUTHORIZED);
            }

            //4.对当前的请求对象进行增强,让它会携带令牌的信息dsad adda 
            request.mutate().header("Authorization","Bearer "+jwt);
            return chain.filter(exchange);
        } catch (Exception exception) {
            exception.printStackTrace();
            throw new TypicalRepException(ReturnCode.RC500.getCode(),ReturnCode.RC500.getMessage());
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
